﻿using Iworld.Backstage.Framework;
using Iworld.Backstage.Framework.AdministratorService;
using Iworld.Toolkit.Helper;
using Iworld.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Iworld.Backstage
{
      [View(Page.管理员列表)]
    public partial class AdministratorListPage : UserControl
    {
        public AdministratorListPage()
        {
            InitializeComponent();
        }

        private void CreateAdministrator(object sender, RoutedEventArgs e)
        {
            CreateAdministratorWindow cwin = new CreateAdministratorWindow();
            cwin.Closed += Closed;
            cwin.Show();
        }

        void Closed(object sender, EventArgs e)
        {
            ChildWindow cw = sender as ChildWindow;
            if (cw.DialogResult == true)
            {
                AdministratorListViewModel v = this.DataContext as AdministratorListViewModel;
                v.RefreshCommand.Execute(1);
            }
        }

        private void EditAdministrator(object sender, RoutedEventArgs e)
        {
            EditAdministratorWindow ewin = new EditAdministratorWindow() {Info = XamlHelper.GetDataContext<AdministratorExport>(sender) };
            ewin.Closed += Closed;
            ewin.Show(); 
        }

        private void Remove(object sender, RoutedEventArgs e)
        {
            ConfirmPrompt cp = new ConfirmPrompt() { Info = "删除之后不可恢复,确认删除吗?" };
            cp.Closed += (s, a) =>
            {
                if(cp.DialogResult == true)
                {
                    AdministratorExport ae = XamlHelper.GetDataContext<AdministratorExport>(sender);
                    AdministratorServiceClient client = new AdministratorServiceClient();
                    client.RemoveAdministratorCompleted += client_RemoveAdministratorCompleted;
                    client.RemoveAdministratorAsync(new RemoveAdministratorImport()
                    {
                        Id = ae.Id,
                        Token = DataManager.GetValue<AdministratorExport>(DataKey.Administrator_Info).Token
                    });
                }
            };       
            cp.Show();
        }

        void client_RemoveAdministratorCompleted(object sender, RemoveAdministratorCompletedEventArgs e)
        {
            if (e.Result.Success)
            {
                new ErrorPrompt() { Info = "移除成功" }.Show();
                AdministratorListViewModel v = this.DataContext as AdministratorListViewModel;
                v.RefreshCommand.Execute(1);
            }
            else
            {
                new ErrorPrompt() { Info = e.Result.Error }.Show();
            }
        }
    }
}
